<?php

namespace App\Providers;

use App\Services\Code;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application Services.
     *
     * @return void
     */
    public function register()
    {
        //
    }

    /**
     * Bootstrap any application Services.
     *
     * @return void
     */
    public function boot()
    {
        //
        Validator::extend('unique_data', function($attribute, $value, $parameters){
            if(!isset($parameters[0])){
                return response()->json(Code::message('error unique_data not has'));
            }
            $db = DB::table($parameters[0]);
            //检测字段名字
            $column_name = $attribute;
            if(isset($parameters[1])){
                $column_name = $parameters[1];
            }
            //检测第三个参数是否包含并且不等于
            if(isset($parameters[2]) && request()->has($parameters[2])){
                $db->where($parameters[2],'!=',request()->input($parameters[2]));
            }
            return !$db->where($column_name,$value)->whereNull('deleted_at')->exists();
        });
        Validator::extend('exists_data', function($attribute, $value, $parameters){
            if(!isset($parameters[0])){
                return response()->json(Code::message('error exists_data not has'));
            }
            $db = DB::table($parameters[0]);
            //检测字段名字
            $column_name = $attribute;
            if(isset($parameters[1])){
                $column_name = $parameters[1];
            }
            //检测第三个参数是否包含并且不等于
            if(isset($parameters[2]) && request()->has($parameters[2])){
                $db->where($parameters[2],'!=',request()->input($parameters[2]));
            }
            return $db->where($column_name,$value)->whereNull('deleted_at')->exists();
        });
    }
}
